import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { SearchOutlined } from '@ant-design/icons';
import { Input, Row, Col, Select, Tag } from 'antd';
import _ from 'lodash';
import { Filter, getTypes, getCollectors, getDefaultTypes, Record } from '@/pages/metricsBuiltin/services';
import Markdown from '@/components/Markdown';
import { getUnitLabel } from '@/pages/dashboard/Components/UnitPicker/utils';
import MetricsList from './MetricsList';

interface Props {
  onSelect: (expression: string, metric: Record) => void;
  setOpen: (open: boolean) => void;
}

export default function Content(props: Props) {
  const { t } = useTranslation('promQLInput');
  const { onSelect, setOpen } = props;
  const [filter, setFilter] = useState({} as Filter);
  const [typesList, setTypesList] = useState<string[]>([]);
  const [collectorsList, setCollectorsList] = useState<string[]>([]);
  const [defaultTypesList, setDefaultTypesList] = useState<string[]>([]);
  const [activeMetric, setActiveMetric] = useState<Record>();
  const defaultCollector = localStorage.getItem('promQLInput_builtiinMetrics_defaultCollector') || undefined;

  useEffect(() => {
    getTypes().then((res) => {
      setTypesList(res);
      getCollectors().then((res) => {
        setCollectorsList(res);
        if (!defaultCollector) {
          setFilter({ ...filter, collector: res[0] });
        } else {
          setFilter({ ...filter, collector: defaultCollector });
        }
        getDefaultTypes().then((res) => {
          setDefaultTypesList(res);
        });
      });
    });
  }, []);

  return (
    <div className='promql-dropdown-built-in-metrics-container' data-oid='jruejvl'>
      <div className='promql-dropdown-built-in-metrics-content' data-oid='xiut25m'>
        <div className='promql-dropdown-built-in-metrics-list' data-oid='kie71c-'>
          <Row gutter={[12, 12]} className='p2' data-oid='avmu3co'>
            <Col span={24} data-oid='xklv4df'>
              <Input
                prefix={<SearchOutlined data-oid='re.tbco' />}
                value={filter.query}
                onChange={(e) => {
                  setFilter({ ...filter, query: e.target.value });
                }}
                placeholder={t('builtinMetrics.query_placeholder')}
                data-oid='1kbf2us'
              />
            </Col>
            <Col span={12} data-oid='tu1y0lm'>
              <Select
                value={filter.typ}
                onChange={(val) => {
                  setFilter({ ...filter, typ: val });
                }}
                options={_.map(typesList, (item) => {
                  return {
                    label: item,
                    value: item,
                  };
                })}
                showSearch
                optionFilterProp='label'
                placeholder={t('metricsBuiltin:typ')}
                allowClear
                style={{ width: '100%' }}
                data-oid='2ovn:sw'
              />
            </Col>
            <Col span={12} data-oid='8la671n'>
              <Select
                value={filter.collector}
                onChange={(val) => {
                  setFilter({ ...filter, collector: val });
                  if (val) {
                    localStorage.setItem('promQLInput_builtiinMetrics_defaultCollector', val);
                  } else {
                    localStorage.removeItem('promQLInput_builtiinMetrics_defaultCollector');
                  }
                }}
                options={_.map(collectorsList, (item) => {
                  return {
                    label: item,
                    value: item,
                  };
                })}
                showSearch
                optionFilterProp='label'
                placeholder={t('metricsBuiltin:collector')}
                allowClear
                style={{ width: '100%' }}
                data-oid='21_.f14'
              />
            </Col>
          </Row>
          <div className='promql-dropdown-built-in-metrics-default-types pl2 pr2' data-oid='tle1dfv'>
            {_.map(defaultTypesList, (item) => {
              return (
                <Tag
                  key={item}
                  color='purple'
                  onClick={() => {
                    setFilter({ ...filter, typ: item });
                  }}
                  data-oid='_vjpkgm'
                >
                  {item}
                </Tag>
              );
            })}
          </div>
          {!_.isEmpty(filter) && (
            <MetricsList
              filter={filter}
              activeMetric={activeMetric}
              setActiveMetric={setActiveMetric}
              onSelect={(expression, metric) => {
                onSelect(expression, metric);
                setOpen(false);
              }}
              data-oid='5xr8_5y'
            />
          )}
        </div>
        {activeMetric && (
          <div className='promql-dropdown-built-in-metrics-detail' data-oid='45_urev'>
            <div className='promql-dropdown-built-in-metrics-detail-title' data-oid='t8.ppoy'>
              {activeMetric?.name}
            </div>
            <div className='promql-dropdown-built-in-metrics-detail-row' data-oid='mm0w45j'>
              <div className='promql-dropdown-built-in-metrics-detail-label' data-oid='-vefsrf'>
                {t('metricsBuiltin:typ')}：
              </div>
              <div className='promql-dropdown-built-in-metrics-detail-value' data-oid='ue8t8:v'>
                {activeMetric?.typ}
              </div>
            </div>
            <div className='promql-dropdown-built-in-metrics-detail-row' data-oid='_jf:cdo'>
              <div className='promql-dropdown-built-in-metrics-detail-label' data-oid='93:6o1k'>
                {t('metricsBuiltin:collector')}：
              </div>
              <div className='promql-dropdown-built-in-metrics-detail-value' data-oid='8quspz2'>
                {activeMetric?.collector}
              </div>
            </div>
            <div className='promql-dropdown-built-in-metrics-detail-row' data-oid='e_a4np8'>
              <div className='promql-dropdown-built-in-metrics-detail-label' data-oid='r:s5s-n'>
                {t('metricsBuiltin:expression')}：
              </div>
              <div className='promql-dropdown-built-in-metrics-detail-value' data-oid='63wg4u3'>
                {activeMetric?.expression}
              </div>
            </div>
            <div className='promql-dropdown-built-in-metrics-detail-row' data-oid='8taluto'>
              <div className='promql-dropdown-built-in-metrics-detail-label' data-oid='y_e4g7_'>
                {t('metricsBuiltin:unit')}：
              </div>
              <div className='promql-dropdown-built-in-metrics-detail-value' data-oid='pmfyp3p'>
                {activeMetric?.unit ? getUnitLabel(activeMetric.unit, true) : '-'}
              </div>
            </div>
            <div
              className='promql-dropdown-built-in-metrics-detail-row'
              style={{
                overflow: 'hidden',
              }}
              data-oid='e9pchbk'
            >
              <div className='promql-dropdown-built-in-metrics-detail-label' data-oid='1rgxr3u'>
                {t('metricsBuiltin:note')}：
              </div>
              <div
                className='promql-dropdown-built-in-metrics-detail-value'
                style={{
                  overflowY: 'auto',
                }}
                data-oid='vwv:yor'
              >
                {activeMetric?.note ? <Markdown content={activeMetric?.note} data-oid='mdg15vm'></Markdown> : '-'}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
